<script>

// ------- Components -------
import Block from '../Block'
import ValueWithDateInput from '../ValueWithInput/WithDate.vue'
import ValueWithInput from '../ValueWithInput/WithInput.vue'
import ValueWithNumberInput from '../ValueWithInput/WithNumberInput.vue'
import ValueWithSelector from '../ValueWithInput/WithSelector.vue'
import EmergencyContactForm from '@/components/EmergencyContact/index'
import AddressSelector from '../ValueWithInput/withAddress'

import SchoolSelector from '../Selector/school.vue'
import BankSelector from '../Selector/bank.vue'

import ImgCropper from '@/components/ImageCropper/index.vue'
import TagPreview from '@/views/personnel-files/components/TagPreview/TagPreview.vue'
import ValueWithUpload from '../ValueWithInput/withUpload.vue'
import BusinessCardAnalysis from '@/views/personnel-files/components/BusinessCardAnalysis/BusinessCardAnalysis.vue'

// ------------------
import { getAddress, uploadFile } from '@/api/basic'
import { isObject, value } from '@/utils/kris_utils'
import { cloneDeep } from 'lodash-es'
import { mapGetters } from 'vuex'

export default {
  components: {
    Block,
    ValueWithDateInput,
    ValueWithInput,
    ValueWithNumberInput,
    ValueWithSelector,
    EmergencyContactForm,

    SchoolSelector,
    BankSelector,
    AddressSelector,
    ImgCropper,
    TagPreview,
    ValueWithUpload,
    BusinessCardAnalysis
  },
  props: {
    isEditing: {
      type: Boolean,
      required: true,
      default: false
    },
    profile: {
      required: true,
      default() {
        return null
      }
    }
  },
  data() {
    return {
      genderOptions: [
        { label: '男', value: 1 },
        { label: '女', value: 0 },
        { label: '不详', value: 3 }
      ],

      registeredResidenceTypeOptions: [
        { label: '农村', value: 1 },
        { label: '城市', value: 0 }
      ],

      educationTypeOptions: [
        { label: '成人教育', value: 1 },
        { label: '自考', value: 0 },
        { label: '统招', value: 2 }
      ],

      schoolSelector: {
        options: [],
        isLoading: false
      },

      bankSelector: {
        options: [],
        isLoading: false
      },

      imageViewer: {
        visible: false,
        current: 'backOfIDCard'
      },

      emergencyContactFormDialog: {
        visible: false
      },

      switchDormDialog: {
        visible: false
      },

      testPath: [],
      uploadoneInchPhotoVisible: false,
      profileBackup: null,
      businessCardAnalysisDialog: {
        visible: false,
        info: {
          title: [],
          email: [],
          fax: []
        }
      }
    }
  },
  computed: {
    ...mapGetters(['defaultCompany']),
    labelStyles() {
      return {}
    },
    contentStyles() {
      return {}
    },
    handleEmergencyContact() {
      return this.profile.emergencyContact ? this.profile.emergencyContact : {}
    }

  },
  methods: {
    handleOpenEmergencyContactDialog() {
      this.profileBackup = cloneDeep(this.profile)
      this.emergencyContactFormDialog.visible = true
    },

    emergencyContactFormDialogCancel() {
      this.emergencyContactFormDialog.visible = false
      this.profile.emergencyContact = this.profileBackup.emergencyContact
      this.profileBackup = null
    },

    cropUploadSuccess(e) {
      console.log('e ------>', e)
      this.profile.oneInchPhoto = e.path
    },
    value,
    async getAddress(id) {
      const result = await getAddress(id)
        .catch(err => {
          throw new Error('获取地址失败', err)
        })

      if (result.code !== 200 || !Array.isArray(result.data)) { throw new Error('获取地址失败') }

      return result
    },
    emergencyContactFormatter(emergencyContact) {
      if (!isObject(emergencyContact)) { return '-' }

      const { name, relationship, contact } = emergencyContact
      if (
        (typeof name !== 'string' || name.trim() === '') ||
        (typeof contact !== 'string' || contact.trim() === '')
      ) { return '-' }

      return `${name} ${relationship} ${contact}`
    },
    openURL(url) {
      window.location.href = url
    },

    openViewer(type) {
      this.imageViewer.current = type
      this.imageViewer.visible = true
    },
    async onUploadConfirm(e) {
      console.log('e --------->', e)
      this.businessCardAnalysisDialog.info = e.result?.data?.analysis?.result
      this.profile.bus_card = e.result?.data?.path

      const loading = this.$loading({
        lock: true,
        text: '名片识别中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      loading.close()
      this.businessCardAnalysisDialog.visible = true
    },

    handleBusinessCardAnalysisConfirm(e) {
      console.log('e --------->', e)
      this.profile.email = e?.email
      this.profile.fax = e?.fax
      this.profile.title = e?.title
    },

    async onUploadAvatarConfirm(e) {
      this.profile.picture = e.result?.data?.path
      const file = e.file.raw
      const watermarkType = this.defaultCompany.id === 1
        ? 'tzmc' : this.defaultCompany.name

      const loading = this.$loading({
        lock: true,
        text: '头像添加水印中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      const formData = new FormData()
      formData.append('file', file)
      formData.append('iswatermark', 1)
      formData.append('watermarkType', watermarkType)

      const res = await uploadFile(formData)
        .catch(err => {
          this.$message.error('头像水印添加失败', err)
        })

      this.profile.picture_watermark = res.data.path

      loading.close()
      this.$message.success('处理成功')
    }
  }
}
</script>

<template>
  <Block title="员工档案">
    <!-- <template #extra v-if="isEditing">
            <el-button size="mini" :loading="$attrs.isSubmitting" @click="$emit('save')">保存</el-button>
        </template> -->
    <template #extra>
      <slot name="extra" />
    </template>

    <div class="company-archives-container">
      <table class="company-archives">
        <tbody>
          <tr>
            <td class="label">姓名</td>
            <td class="value">
              <ValueWithInput v-model="profile.name" :is-editing="isEditing" size="mini" placeholder="请填写姓名" />
            </td>

            <td class="label">手机号</td>
            <td class="value" colspan="2">
              <ValueWithInput v-model="profile.phone" :is-editing="isEditing" size="mini" placeholder="请填写手机号" />
            </td>

            <td class="value" style="padding: 8px;text-align: center;" rowspan="4">
              <el-image :src="profile.oneInchPhoto || ''" style="width: 162px;height: 195px;" fit="cover">
                <div slot="error" class="image-error-slot">
                  <i class="el-icon-picture-outline icon" />
                </div>
              </el-image>
              <!-- @click="$emit('uploadFile','oneInchPhoto')" -->
              <el-button v-if="isEditing" type="text" @click="uploadoneInchPhotoVisible = true">
                <i class="el-icon-refresh" />
                更换
              </el-button>
            </td>
          </tr>

          <tr>
            <td class="label">邮箱</td>
            <td class="value">
              <ValueWithInput v-model="profile.email" :is-editing="isEditing" size="mini" placeholder="请填写邮箱" />
            </td>

            <td class="label">性别</td>
            <td class="value" colspan="2">
              <ValueWithSelector
                v-model="profile.gender"
                size="mini"
                filterable
                placeholder="请选择性别"
                style="width: 100%;"
                :is-editing="isEditing"
                :options="genderOptions"
              />

            </td>
          </tr>

          <tr>
            <td class="label">出生年月</td>
            <td class="value">
              <ValueWithDateInput
                v-model="profile.birthday"
                :is-editing="isEditing"
                size="mini"
                style="width: 100%;"
                placeholder="请选择出生年月"
              />
            </td>

            <td class="label">民族</td>
            <td class="value" colspan="2">

              <ValueWithSelector
                v-model="profile.nation"
                size="mini"
                placeholder="请选择民族"
                style="width: 100%;"
                filterable
                :is-editing="isEditing"
                :options="$attrs.nation_options"
              />
            </td>
          </tr>

          <tr>
            <td class="label">身份证有效期</td>
            <td class="value">
              <ValueWithDateInput
                v-model="profile.idPeriodOfValidity"
                :is-editing="isEditing"
                size="mini"
                style="width: 100%;"
                placeholder="请选择身份证有效期"
              />
            </td>

            <td class="label">身份证</td>
            <td class="value" colspan="2">
              <ValueWithInput v-model="profile.idNo" :is-editing="isEditing" size="mini" placeholder="请填写身份证" />
              &nbsp;
              <el-button type="text" @click="openViewer('frontOfIDCard')">
                <i class="el-icon-view" />
                查看
              </el-button>

              <el-button v-if="isEditing" type="text" @click="$emit('updateIDCard')">
                <i class="el-icon-refresh" />
                更换
              </el-button>
            </td>
          </tr>

          <tr>
            <td class="label">现住地址</td>
            <td class="value">
              <ValueWithInput
                v-model="profile.currentAddress"
                :is-editing="isEditing"
                size="mini"
                placeholder="请填写现住地址"
              />
            </td>

            <td class="label">婚姻状态</td>
            <td class="value">
              <ValueWithSelector
                v-model="profile.marriageStatus"
                size="mini"
                filterable
                placeholder="请选择婚姻状态"
                style="width: 100%;"
                :is-editing="isEditing"
                :options="$attrs.marriage_statuses_options"
              />
            </td>

            <td class="label">学历</td>
            <td class="value">
              <ValueWithSelector
                v-model="profile.educationLevel"
                size="mini"
                filterable
                placeholder="请选择学历"
                style="width: 100%;"
                :is-editing="isEditing"
                :options="$attrs.educational_level_options"
              />
            </td>
          </tr>

          <tr>
            <td class="label">身高cm</td>
            <td class="value">
              <ValueWithNumberInput v-model="profile.height" :is-editing="isEditing" size="mini" placeholder="请填写身高" />
            </td>

            <td class="label">体重(KG)</td>
            <td class="value">
              <ValueWithNumberInput v-model="profile.weight" :is-editing="isEditing" size="mini" placeholder="请填写体重" />
            </td>

            <td class="label">户口性质</td>
            <td class="value">
              <ValueWithSelector
                v-model="profile.registeredResidenceType"
                size="mini"
                filterable
                placeholder="请选择户口性质"
                style="width: 100%;"
                :is-editing="isEditing"
                :options="registeredResidenceTypeOptions"
              />
            </td>
          </tr>

          <tr>
            <td class="label">学历性质</td>
            <td class="value">
              <ValueWithSelector
                v-model="profile.educationType"
                size="mini"
                filterable
                placeholder="请选择学历性质"
                style="width: 100%;"
                :is-editing="isEditing"
                :options="educationTypeOptions"
              />
            </td>

            <td class="label">毕业院校</td>
            <td class="value">
              <SchoolSelector
                v-model="profile.school"
                size="mini"
                placeholder="请选择毕业学校"
                style="width: 100%;"
                :is-editing="isEditing"
              />
            </td>

            <td class="label">毕业日期</td>
            <td class="value">
              <ValueWithDateInput
                v-model="profile.graduationDate"
                :is-editing="isEditing"
                size="mini"
                style="width: 100%;"
                placeholder="请选择毕业日期"
              />
            </td>
          </tr>

          <tr>
            <td class="label">所学专业</td>
            <td class="value">
              <ValueWithInput v-model="profile.major" :is-editing="isEditing" size="mini" placeholder="请填写所学专业" />
            </td>

            <td class="label">特长</td>
            <td class="value">
              <ValueWithInput v-model="profile.speciality" :is-editing="isEditing" size="mini" placeholder="请填写技能特长" />
            </td>

            <td class="label">银行卡号</td>
            <td class="value">
              <ValueWithInput
                v-model="profile.bankAccountNumber"
                :is-editing="isEditing"
                size="mini"
                placeholder="请填写银行卡号"
              />
            </td>
          </tr>

          <tr>
            <td class="label">开户行</td>
            <td class="value">
              <BankSelector
                v-model="profile.bank"
                size="mini"
                placeholder="请选择开户行"
                style="width: 100%;"
                :is-editing="isEditing"
              />
            </td>

            <td class="label">政治面貌</td>
            <td class="value">
              <ValueWithSelector
                v-model="profile.politicalStatus"
                size="mini"
                filterable
                placeholder="请选择政治面貌"
                style="width: 100%;"
                :is-editing="isEditing"
                :options="$attrs.politics_options"
              />
            </td>

            <td class="label">社保编号</td>
            <td class="value">
              <ValueWithInput
                v-model="profile.socialSecurityNumber"
                :is-editing="isEditing"
                size="mini"
                placeholder="请填写社保编号"
              />
            </td>
          </tr>

          <tr>
            <td class="label">紧急联系人</td>
            <td class="value">
              {{ emergencyContactFormatter(profile.emergencyContact) }}
              <el-button v-if="isEditing" type="text" @click="handleOpenEmergencyContactDialog">
                <i class="el-icon-edit-outline" />
                编辑
              </el-button>
            </td>

            <td class="label">简历附件</td>
            <td class="value">
              <el-button v-if="profile.resumeAttachment" type="text" @click="openURL(profile.resumeAttachment)">
                <i class="el-icon-download" />
                下载
              </el-button>
              <span v-else>-</span>

              <el-button v-if="isEditing" type="text" @click="$emit('uploadFile', 'resumeAttachment')">
                <i class="el-icon-refresh" />
                更换
              </el-button>
            </td>

            <td class="label">户籍地</td>
            <td class="value">
              <AddressSelector
                v-model="profile.domicile"
                :is-editing="isEditing"
                size="mini"
                style="width: 100%;"
                placeholder="请选择户籍地"
              />
            </td>
          </tr>

          <tr>
            <td class="label">现住地</td>
            <td class="value">
              <ValueWithInput
                v-model="profile.currentAddress2"
                :is-editing="isEditing"
                size="mini"
                placeholder="请填写现住地"
              />
            </td>

            <td class="label">家庭电话</td>
            <td class="value">
              <ValueWithInput v-model="profile.homePhone" :is-editing="isEditing" size="mini" placeholder="请填写家庭电话" />
            </td>

            <td class="label">电脑能力</td>
            <td class="value">
              <ValueWithInput
                v-model="profile.computerSkills"
                :is-editing="isEditing"
                size="mini"
                type="textarea"
                placeholder="请填写电脑能力"
              />
            </td>
          </tr>

          <tr>
            <td class="label">微信号</td>
            <td class="value">
              <ValueWithInput v-model="profile.wx_number" :is-editing="isEditing" size="mini" placeholder="请填写微信号" />
            </td>

            <td class="label">传真</td>
            <td class="value">
              <ValueWithInput v-model="profile.fax" :is-editing="isEditing" size="mini" placeholder="请填写传真" />
            </td>

            <td class="label">头衔</td>
            <td class="value">
              <TagPreview :list.sync="profile.title" :is-editing="isEditing" />
            </td>
          </tr>

          <tr>
            <td class="label">名片</td>
            <td class="value">
              <ValueWithUpload
                :is-editing="isEditing"
                :download-address="profile.bus_card_watermark"
                :form-data="{ folder: 'card', type: 'businessCard', analysis: 1 }"
                upload-field="bus_card"
                @onConfirm="onUploadConfirm"
              />
            </td>
            <td class="label">电子名片头像</td>
            <td class="value" colspan="3">
              <ValueWithUpload
                :is-editing="isEditing"
                :download-address="profile.picture_watermark"
                :form-data="{ folder: 'card' }"
                upload-field="bus_card"
                @onConfirm="onUploadAvatarConfirm"
              />
            </td>
          </tr>

        </tbody>
      </table>
    </div>

    <el-dialog title="身份证" :visible.sync="imageViewer.visible" width="30%">
      <el-tabs v-model="imageViewer.current">
        <el-tab-pane label="身份证正面" name="frontOfIDCard">
          <el-image v-if="profile.frontOfIDCard" :src="profile.frontOfIDCard" />
        </el-tab-pane>

        <el-tab-pane label="身份证反面" name="backOfIDCard">
          <el-image v-if="profile.backOfIDCard" :src="profile.backOfIDCard" />
        </el-tab-pane>

        <el-tab-pane label="一寸照" name="oneInchPhoto">
          <el-image v-if="profile.oneInchPhoto" :src="profile.oneInchPhoto" />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <el-dialog
      title="紧急联系人"
      width="30%"
      :close-on-click-modal="false"
      :visible.sync="emergencyContactFormDialog.visible"
    >
      <EmergencyContactForm v-model="profile.emergencyContact" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="emergencyContactFormDialogCancel">
          取 消
        </el-button>

        <el-button type="primary" @click="emergencyContactFormDialog.visible = false">
          确 定
        </el-button>
      </div>
    </el-dialog>

    <ImgCropper
      v-model="uploadoneInchPhotoVisible"
      url="/v1/upload/file"
      field="file"
      :params="{
        folder: 'test'
      }"
      :width="295"
      :height="413"
      no-square
      no-circle
      @crop-upload-success="cropUploadSuccess"
    />

    <BusinessCardAnalysis
      :visible.sync="businessCardAnalysisDialog.visible"
      :info="businessCardAnalysisDialog.info"
      @confirm="handleBusinessCardAnalysisConfirm"
    />
  </Block>
</template>

<style lang="scss">
.company-archives-container {
  .company-archives {
    width: 100%;
    border: 1px solid #DCDFE6;
    border-collapse: collapse;

    .label,
    .value {
      width: 200px;
      text-align: center !important;
      color: #333333;
      padding: 4px 20px;
      margin: 0;
      border-bottom: 1px solid #DCDFE6;
      border-left: 1px solid #DCDFE6;
      font-size: 14px;
      height: 44px;
    }

    .label:first-child,
    .value:first-child {
      border-left: none;
    }

    tr:last-child {

      .label,
      .value {
        border-bottom: none;
      }
    }

    .label {
      width: 150px;
      background-color: #F5F7FA;
      font-weight: bold;
      color: #909399;

    }

    .value {
      background-color: #FFFFFF;
    }

    .image-error-slot {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #f5f7fa;

      >.icon {
        font-size: 30px;
        color: #909399;
      }
    }
  }
}
</style>
